package cn.chinaunicom.sdsi.gacx.quartz;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import cn.chinaunicom.sdsi.gacx.author.service.AuthorService;
import cn.chinaunicom.sdsi.gacx.quartz.dao.mybatis.GaTaskConfigMapper;
import cn.chinaunicom.sdsi.gacx.quartz.service.QuartzService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Component
@PropertySource("classpath:quartz.properties")
public class QuartzTaskManager {
	@Autowired
	private QuartzService quartzService;
	private final String type = "0";// 默认取0的定时任务
	private final Map taskListMap = new HashMap();

	// 配置表取定时执行时间     自动执行执行一次
	@Scheduled(cron = "${taskManagerCron}")
	public void quartzTaskMonitor() {
		System.out.println("监控定时类任务扫描开始...........");
		JSONObject jObject = quartzService.selectAllTaskByType(type);
		JSONArray cronArray = jObject.getJSONArray("data");
		for (int i = 0; i < cronArray.size(); i++) {
			JSONObject job = cronArray.getJSONObject(i);
			String jobId = job.getString("jobId");
			String doFrequency = job.getString("doFrequency");
			String isModify = job.getString("isModify");
			String doClass = job.getString("doClass");

			// 存在
			if (taskListMap.containsKey(jobId)) {
				if (isModify.equals("1")) {
					System.out.println("重新修改定时器时间..........."+jobId);
					modifyJobTime(jobId, doFrequency);
					quartzService.updateJobIsModify(jobId);
					
				}
			} else {// 不存在
				try {
					System.out.println("增加定时器..........."+jobId);
					Class jobclass = Class.forName(doClass);
					addJob(jobId, jobclass, doFrequency);
					taskListMap.put(jobId, jobId);
				} catch (Exception e) {
					System.out.println("增加定时器异常,请检查配置"+e.getMessage());
				}
			}
		}
	}

	private void addJob(String jobName, Class doClass, String cron) {
		QuartzManager.addJob(jobName, doClass, cron);
	}

	private void removeJob(String jobName) {
		QuartzManager.removeJob(jobName);
	}

	private void modifyJobTime(String jobName, String cron) {
		QuartzManager.modifyJobTime(jobName, cron);
	}

}